const { DataTypes } = require('sequelize');
const sequelize = require('../config/database');

const User = sequelize.define('User', {
    id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    account: {
        type: DataTypes.STRING(20),
        allowNull: false,
        unique: true
    },
    password: {
        type: DataTypes.STRING(255),
        allowNull: false
    },
    avatar: {
        type: DataTypes.STRING(255),
        allowNull: true,
        defaultValue: '/uploads/avatars/default.png' // 默认头像
    }
}, {
    tableName: 'Users',
    timestamps: true
});

// 创建好友关系表
const Friendship = sequelize.define('Friendship', {
    id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    status: {
        type: DataTypes.STRING(20),
        allowNull: false,
        defaultValue: 'pending',
        validate: {
            isIn: [['pending', 'accepted', 'rejected']]
        }
    }
}, {
    tableName: 'Friendships',
    timestamps: true
});

// 设置关联关系
Friendship.belongsTo(User, { as: 'sender', foreignKey: 'userId' });
Friendship.belongsTo(User, { as: 'receiver', foreignKey: 'friendId' });

// 设置多对多关系
User.belongsToMany(User, {
    through: Friendship,
    as: 'friends',
    foreignKey: 'userId',
    otherKey: 'friendId'
});

User.belongsToMany(User, {
    through: Friendship,
    as: 'friendRequests',
    foreignKey: 'friendId',
    otherKey: 'userId'
});

module.exports = { User, Friendship }; 